<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachRef" :model="seachForm">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="phone" hide-label>
                    <a-input-group>
                      <a-select
                        style="width: 50%"
                        @change="seachTypeChangeFn"
                        v-model="seachType"
                        placeholder="first"
                        :options="seachTypeList"
                      />
                      <a-input
                        style="width: 50%"
                        v-model="seachTypeText"
                        allow-clear
                        placeholder="请输入搜索条件"
                      >
                        <!-- <template #suffix>
                          <icon-plus @click="openTypeMore" style="cursor: pointer" />
                        </template> -->
                      </a-input>
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      v-model="seachForm.addTime"
                      style="width: 100%"
                      show-time
                      placeholder="请选择开始时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(7, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      v-model="seachForm.endTime"
                      style="width: 100%"
                      show-time
                      placeholder="请选择结束时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(7, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button type="primary" html-type="submit" @click="doRefresh"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button html-type="submit" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button type="primary" @click="addItem">
            <template #default>新建</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: bordered, cell: bordered }"
          :stripe="(striped as boolean)"
          :loading="tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          :scrollbar="{ type: 'track', outerClass: '', outerStyle: '' }"
          :scroll="{ x: 1500 }"
          table-layout-fixed
          :draggable="{ type: 'handle', width: 40 }"
          @change="handleChange"
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :width="item.width"
              :ellipsis="true"
              :tooltip="true"
              :title="(item.title as string)"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
            >
              <template v-if="item.key === 'colors'" #cell="{ record }">
                <div
                  v-if="record.type == 0"
                  :style="{
                    background: record.fillColor,
                    height: '30px',
                    borderRadius: '5px',
                    textAlign: 'center',
                    color: record.fontColor,
                    border: `1px solid ${record.frameColor}`,
                    lineHeight: '30px',
                    padding: '0 10px',
                  }"
                >
                  {{ record.name }}
                </div>
                <img v-else :src="record.img" style="height: 30px" mode="heightFix" alt="" />
              </template>

              <template v-if="item.key === 'actions'" #cell="{ record }">
                <a-space :size="2">
                  <a-button
                    style="padding: 0px 4px"
                    type="text"
                    @click="updateItem(record)"
                    size="small"
                    >编辑</a-button
                  >
                  <a-button
                    style="padding: 0px 4px"
                    type="text"
                    size="small"
                    @click="onCopy(record)"
                    >复制</a-button
                  >

                  <a-button
                    style="padding: 0px 4px"
                    type="text"
                    status="danger"
                    @click="infoDelete(record)"
                    size="small"
                  >
                    删除
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
    </TableBody>
    <a-modal v-model:visible="visible" title-align="start" @before-close="closeInfo" :title="title">
      <a-form ref="infoRef" :model="infoForm" label-align="left">
        <a-form-item
          field="name"
          :rules="[{ required: true, message: '请输入标签名称' }]"
          asterisk-position="end"
          label="标签名称"
        >
          <a-input v-model="infoForm.name" placeholder="请输入标签名称" />
        </a-form-item>
        <a-form-item
          field="sort"
          :rules="[{ required: true, message: '请输入标签排序' }]"
          asterisk-position="end"
          label="标签排序"
        >
          <a-input-number hideButton v-model="infoForm.sort" placeholder="请输入标签排序" />
        </a-form-item>
        <a-form-item field="type" label="标签类型">
          <a-radio-group v-model="infoForm.type" class="radio-bcg">
            <a-radio :value="0">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div>
                  </div>
                  <div className="custom-radio-card-title">文字</div>
                </div>
              </template>
            </a-radio>
            <a-radio :value="1">
              <template #radio="{ checked }">
                <div style="display: flex" :class="{ 'custom-radio-card-checked': checked }">
                  <div className="custom-radio-card-mask">
                    <div className="custom-radio-card-mask-dot"></div>
                  </div>
                  <div className="custom-radio-card-title">图片</div>
                </div>
              </template>
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="post" label="字体颜色" v-if="infoForm.type == 0">
          <color-picker format="rgb" v-model:pureColor="infoForm.fontColor" />
        </a-form-item>
        <a-form-item field="post" label="填充颜色" v-if="infoForm.type == 0">
          <color-picker
            format="rgb"
            shape="square"
            use-type="gradient"
            v-model:gradientColor="infoForm.fillColor"
          />
        </a-form-item>
        <a-form-item field="post" label="边框颜色" v-if="infoForm.type == 0">
          <color-picker format="rgb" shape="square" v-model:pureColor="infoForm.frameColor" />
        </a-form-item>
        <a-form-item label="标签图片" field="couponImg" v-if="infoForm.type == 1">
          <a-upload
            action="/app/file/upload"
            :show-file-list="false"
            @success="onSuccessBcg"
            :image-preview="true"
          >
            <template #upload-button>
              <div class="arco-upload-list-picture custom-upload-avatar" v-if="infoForm.img">
                <img :src="infoForm.img" />
                <div class="arco-upload-list-picture-mask">
                  <IconEdit />
                </div>
              </div>
              <div class="arco-upload-picture-card" v-else>
                <div class="arco-upload-picture-card-text">
                  <IconPlus />
                </div>
              </div>
              <!-- </div> -->
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item field="isRead" label="标签预览">
          <div
            v-if="infoForm.type == 0"
            :style="{
              background: infoForm.fillColor,
              height: '30px',
              borderRadius: '5px',
              textAlign: 'center',
              color: infoForm.fontColor,
              border: `1px solid ${infoForm.frameColor}`,
              lineHeight: '30px',
              padding: '0 10px',
            }"
          >
            {{ infoForm.name }}
          </div>
          <img v-else :src="infoForm.img" style="height: 30px" mode="heightFix" alt="" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-space>
          <a-button @click="closeInfo">取消</a-button>
          <a-button type="primary" @click="confItem">确定</a-button>
        </a-space>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { get, post } from '@/api/http'
  import { onMounted, reactive, ref } from 'vue'
  import { useRowKey, useTable } from '@/hooks/table'
  import {
    productTag,
    productTagAdd,
    productTagUpdate,
    productTagDelete,
    productTagSort,
  } from '@/api/url'
  import { ColorPicker } from 'vue3-colorpicker'
  import 'vue3-colorpicker/style.css'
  import { Message, Modal } from '@arco-design/web-vue'
  const table = useTable()
  const rowKey = useRowKey('id')
  const bordered = ref(false)
  const striped = ref(false)
  const tableLoading = ref(true)
  const visible = ref(false)
  const title = ref('新建标签')
  const tableColumns: any = reactive({
    list: [
      {
        title: '标签ID',
        key: 'id',
        dataIndex: 'id',
        ellipsis: true,
        tooltip: true,
        checked: true,
        width: 100,
      },
      {
        title: '标签名称',
        key: 'name',
        dataIndex: 'name',
        ellipsis: true,
        tooltip: true,
        checked: true,
        width: 234,
      },
      {
        title: '标签样式',
        key: 'colors',
        dataIndex: 'colors',
        checked: true,
        width: 120,
      },

      {
        title: '创建时间',
        key: 'addTime',
        dataIndex: 'addTime',
        width: 232,
        checked: true,
      },
      {
        title: '操作',
        key: 'actions',
        fixed: 'right',
        dataIndex: 'actions',
        width: 150,
        align: 'center',
        checked: true,
      },
    ],
  })
  //搜索项
  const seachRef = ref()
  const seachType = ref('name')
  const seachTypeText = ref('')
  const seachTypeList = ref([
    {
      value: 'id',
      label: '标签ID',
    },
    {
      value: 'name',
      label: '标签名称',
    },
  ])
  const seachForm = ref({
    id: '', //     id
    name: '', //     名称
    addTime: '', //  开始时间
    endTime: '', //  结束时间
  })
  const infoRef = ref()
  const infoForm: any = ref({
    name: '', // 海报名称
    color: '',
    type: 0,
    img: '',
    sort: '',
    fontColor: '',
    frameColor: '',
    fillColor: '',
  })
  //排序
  const handleChange = (_data: any, extra: any) => {
    var sorts: any = []
    _data.forEach((item: any, index: any) => {
      sorts.push({
        id: item.id,
        sort: index,
      })
      // item.sort = index
    })
    post({
      url: productTagSort,
      data: sorts,
    }).then((res) => {
      if (res.code == 0) {
        Message.success(res.msg)
        doRefresh()
      } else {
        Message.error(res.msg)
      }
    })
  }
  //背景图上传
  const onSuccessBcg = (fileItem: any) => {
    infoForm.value.img = fileItem.response.data.path
  }
  //搜索类型切换
  function seachTypeChangeFn() {
    seachForm.value.id = ''
    seachForm.value.name = ''
  }
  //弹窗关闭回调
  function closeInfo() {
    infoRef.value.resetFields()
    infoForm.value = {
      name: '', // 海报名称
      color: '',
      type: 0,
      img: '',
      sort: '',
      fontColor: '#000000',
      frameColor: '#000000',
      fillColor: 'rgba(0, 0, 0, 0)',
    }
    visible.value = false
  }
  function infoDelete(val: any) {
    Modal.warning({
      title: '操作提示',
      titleAlign: 'start',
      content: '确定要删除此标签？',
      hideCancel: false,
      onOk() {
        get({
          url: productTagDelete,
          data: {
            id: val.id,
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          }
        })
      },
    })
  }
  //添加海报
  function addItem() {
    title.value = '新建标签'
    infoForm.value.id = null
    infoForm.value.type = 0
    infoForm.value.fontColor = '#000000'
    infoForm.value.frameColor = '#000000'
    infoForm.value.fillColor = 'rgba(0, 0, 0, 0)'
    visible.value = true
  }

  function onCopy(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要复制标签吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确认',
      onOk: () => {
        post({
          url: productTagAdd,
          data: () => {
            return {
              ...item,
            }
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success('复制成功')
            visible.value = false
            infoRef.value.resetFields()
            doRefresh()
          } else {
            Message.error(res.msg)
          }
        })
      },
    })
  }

  //修改海报
  function updateItem(val: any) {
    title.value = '修改标签'
    if (!val.fontColor) {
      val.fontColor = '#000000'
    }
    if (!val.frameColor) {
      val.frameColor = '#000000'
    }
    if (!val.fillColor) {
      val.fillColor = 'rgba(0, 0, 0, 0)'
    }
    infoForm.value = JSON.parse(JSON.stringify(val))

    visible.value = true
  }
  //添加/修改海报
  function confItem() {
    infoRef.value?.validate().then((error: any) => {
      if (!error) {
        if (!infoForm.value.id) {
          post({
            url: productTagAdd,
            data: () => {
              return {
                ...infoForm.value,
              }
            },
          })
            .then((res) => {
              Message.success(res.msg)
              closeInfo()
              doRefresh()
            })
            .catch(console.log)
        } else {
          post({
            url: productTagUpdate,
            data: () => {
              return {
                ...infoForm.value,
              }
            },
          })
            .then((res) => {
              Message.success(res.msg)
              closeInfo()
              doRefresh()
            })
            .catch(console.log)
        }
      }
    })
  }
  //获取列表
  function doRefresh() {
    seachForm.value[seachType.value] = seachTypeText.value
    get({
      url: productTag,
      data: () => {
        return {
          ...seachForm.value,
        }
      },
    })
      .then((res) => {
        tableLoading.value = false
        table.handleSuccess(res.data)
      })
      .catch(console.log)
  }
  //重置搜索项
  function resetSeach() {
    seachForm.value.id = ''
    seachForm.value.name = ''
    seachForm.value.addTime = ''
    seachForm.value.endTime = ''
    seachTypeText.value = ''
    doRefresh()
  }
  function onUpdateBorder(isBordered: boolean) {
    bordered.value = isBordered
  }
  function onUpdateStriped(isStriped: boolean) {
    striped.value = isStriped
  }
  onMounted(() => {
    doRefresh(1)
  })
</script>

<style lang="scss" scoped></style>
